# coding:utf-8
from .data_collector import DataCollector
import pandas as pd


class StockCrawler(DataCollector):
    stock_type = "创业板"
    stock_codes = ["sz300001", "sz300002", "sz300003", "sz300004", "sz300005"]
    stock_items = []

    def __init__(self):
        DataCollector.__init__(self)
        self.algorithm_name = "股票信息"
        self.ipynb_template_name = "stock_crawler-template.ipynb"

    def implent(self):
        DataCollector.implent(self)
        if self.stock_type == "科创板":
            self.stock_codes = ["sh688001", "sh688002", "sh688003", "sh688005", "sh688006"]
        self.stock_items = []
            
        for stock_code in self.stock_codes:
            url = "http://hq.sinajs.cn/list=" + stock_code
            result = self.http.request(method="GET", url=url)
            text = result.data.decode("gbk").strip()
            items = text[text.find("\"") + 1:-2].split(",")
            if len(items) > 0:
                self.stock_items.append([stock_code, url, "http://image.sinajs.cn/newchart/min/n/%s.gif" % (stock_code), items[30], items[31],
                                    items[0], float(items[1]), float(items[2]), float(items[3]), float(items[4]), float(items[5])])  
        self.df = pd.DataFrame(self.stock_items, columns=["代码", "接口地址", "K线图", "日期", "时间",
                                            "名称", "今日开盘价", "昨日收盘价", "当前价格", "今日最高价", "今日最低价"])

    def prepareIpynbItems(self):
        DataCollector.prepareIpynbItems(self)
        self.ipynb_items["#stock_type#"] = self.stock_type
